#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int num = 10;
#define MAX_PRODUCT 20
pthread_mutex_t mutex;
pthread_cond_t cond;
void * func(void *arg){
    while(1){
        pthread_mutex_lock(&mutex);
        //防止虚假唤醒(操作系统看到一个线程挂起时间太长了，唤醒一下)
        while(num >= MAX_PRODUCT){
            printf("生产者线程发现产品达到上限，挂起\n");
            pthread_cond_wait(&cond, &mutex);
        }
        num++;
        printf("生产者线程生产数据%d\n", num);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }

    return NULL;
}

int main(){
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_t tid;
    int res = pthread_create(&tid, NULL, func, NULL);
    if(res){
        perror("pthread_create");
        exit(EXIT_FAILURE);
    }

    while(1){
        pthread_mutex_lock(&mutex);
        num--;
        printf("消费者线程消费数据%d\n", num);
        pthread_cond_signal(&cond); 
        pthread_mutex_unlock(&mutex);  
        sleep(3);
    }

    pthread_join(tid, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}
